var express = require("express");
var router = express.Router();
//导入 moment
const departmentsModel = require("../../models/departmentsModel");

router.post("/add", async (req, res) => {
  if (!req.body.name || !req.body.manager) {
    res.json({
      code: "1002",
      msg: "格式错误~~",
      data: err,
    });
    return;
  }
  const existingDepartment = await departmentsModel.findOne({
    name: req.body.name,
  });
  if (existingDepartment) {
    return res.status(400).json({
      code: "1003",
      msg: "部门名称已存在，不允许重复~~",
    });
  }
  const data = req.body;
  departmentsModel.create(data, (err, data) => {
    if (err) {
      res.json({
        code: "1002",
        msg: "创建失败~~",
        data: err,
      });
      return;
    }
    res.json({
      code: "1000",
      msg: "创建成功~~",
    });
  });
});
router.get("/page", async (req, res) => {
  try {
    // 模拟部门数据
    let list = await departmentsModel.find().select("-__v");
    list = list.map((item) => {
      const { _id, ...re } = item.toObject();
      return {
        ...re,
        id: _id.toString(),
      };
    });

    function buildTree(data, parentId) {
      const tree = [];

      for (let item of data) {
        if (item.parentId === parentId) {
          const children = buildTree(data, item.id);
          if (children.length > 0) {
            item.children = children;
          }
          tree.push(item);
        }
      }

      return tree;
    }
    // console.log(list);
    const tree = buildTree(list, "");
    res.json({
      code: "200",
      msg: "查询成功~~",
      list: tree,
    });
  } catch (err) {
    res.json({
      code: "1002",
      msg: "查询失败~~",
      data: err,
    });
  }
});
router.get("/check", async (req, res) => {
  try {
    const id = req.query.id;
    const item = await departmentsModel.findOne({ _id: id }).select("-__v");
    const { _id, ...re } = item.toObject();
    res.json({
      data: {
        id: _id,
        ...re,
      },
      code: "200",
      msg: "查询成功~~",
    });
  } catch (err) {
    res.json({
      code: "1002",
      msg: "查询失败~~",
      data: err,
    });
  }
});
router.post("/edit", async (req, res) => {
  const { id, manager, name } = req.body;
  if (!id) {
    return res.json({
      code: "1002",
      msg: "参数有误~~",
    });
  }
  try {
    await departmentsModel.updateOne({ _id: id }, { manager, name });
    res.json({
      code: "0000",
      msg: "编辑成功",
    });
  } catch (err) {
    res.json({
      code: "1002",
      msg: "编辑失败",
    });
  }
});
router.post("/del", async (req, res) => {
  try {
    await departmentsModel.deleteOne({ _id: req.body.id });
    res.json({
      code: "0000",
      msg: "删除成功",
    });
  } catch (err) {
    res.json({
      code: "1002",
      msg: "删除失败",
    });
  }
});
module.exports = router;
